import type { DirectiveBinding } from 'vue';
import { useUserStore } from '@/store';

function checkPermission(el: HTMLElement, binding: DirectiveBinding) {
  const { value } = binding;
  const userStore = useUserStore();
  const { role } = userStore;

  if (Array.isArray(value)) {
    if (value.length > 0) {
      const permissionValues = value;

      const hasPermission = permissionValues.includes(role);
      // 兜底保护：指令可能绑定在组件根节点或元素已被卸载，需判空与防重复
      if (!hasPermission) {
        // 防止重复执行 updated/mounted 时多次移除
        if ((el as any).__perm_removed__) return;
        // 优先通过标准 API 移除
        if (typeof (el as any).remove === 'function') {
          (el as any).remove();
          (el as any).__perm_removed__ = true;
          return;
        }
        // 兼容老浏览器或特殊节点
        if (el && el.parentNode) {
          el.parentNode.removeChild(el);
          (el as any).__perm_removed__ = true;
        }
      }
    }
  } else {
    throw new Error(`need roles! Like v-permission="['admin','user']"`);
  }
}

export default {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    if (!el) return;
    checkPermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    if (!el) return;
    // 若已被移除则无需再次处理
    if ((el as any).__perm_removed__) return;
    checkPermission(el, binding);
  }
};
